package com.htd.erp.model;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;


@Entity
public class Classification extends NamedEntity {

	private static final long serialVersionUID = 3157841210450352624L;

	@ManyToOne(fetch = FetchType.LAZY)
	private Classification parentClassification;
	
	@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "parentClassification")
	private Set<Classification> subClassifications;
	
	@OneToMany
	private List<Product> products;
	
	public Classification() {
	}
	
	public Classification(Classification parentClassification) {
		parentClassification.getSubClassifications().add(this);
		this.parentClassification = parentClassification;
	}

	public boolean isDeletable() {
		return isLeaf() || !hasActiveSubClassifications();
	}

	private boolean hasActiveSubClassifications() {
		for(Classification classification : getSubClassifications()) {
			if(!classification.isDeleted()) {
				return true;
			}
		}
		return false;
	}

	private boolean isLeaf() {
		return getSubClassifications().isEmpty() && getProducts().isEmpty();
	}
	
	public List<Product> getProducts() {
		if(products == null) {
			products = new ArrayList<Product>();
		}
		return products;
	}

	public void setProducts(List<Product> products) {
		this.products = products;
	}

	public Classification getParentClassification() {
		return parentClassification;
	}

	public void setParentClassification(Classification parentClassification) {
		this.parentClassification = parentClassification;
	}

	public Set<Classification> getSubClassifications() {
		if(subClassifications == null) {
			subClassifications = new HashSet<Classification>();
		}
		return subClassifications;
	}

	public void setSubClassifications(Set<Classification> subClassifications) {
		this.subClassifications = subClassifications;
	}
}
